package cn.fl.collection.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.collection.service.IRskCltAuthRebateService;
import cn.fl.collection.service.IRskCltAuthService;
import cn.fl.collection.vo.RskCltAuthRcvAplVO;
import cn.fl.collection.vo.RskCltAuthVO;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.dto.ProjectFlowSHDTO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import com.alibaba.fastjson.JSON;
import fl.ass.facade.constant.AssFileConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
* @Description:    委外催收流程管理Controller
* @Author:         liurong
* @CreateDate:     2020/4/22 15:12
* @Version:        1.0
*/
@Controller
@RequestMapping("/clt/auth/flow")
public class RskCltAuthFlowController {

    /**
     * RskCltAuth 服务层BEAN
     */
    @Autowired
    private IRskCltAuthService rskCltAuthService;

    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    /**
     *ISysUsrService 服务层BEAN
     */
    @Autowired
    private ISysUsrService sysUsrService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 文件上传
     */
    @Autowired
    private IUploadApiService uploadApiService;

    @Autowired
    private IRskCltAuthRebateService rskCltAuthRebateService;

    /**
     * 到委案催收流程附加页面
     */
    @RequestMapping(value = "/toCltAuthFlowPage.do", method = {RequestMethod.GET})
    public ModelAndView toCltAuthFlowPage(HttpServletRequest request) {
        String applyId = request.getParameter("applyId");
        String taskFlag = request.getParameter("flag");
        ModelAndView view = new ModelAndView("collection/flow/cltAuthFlow");
        List<KeyValueVO> payWays = this.sysDictionaryApiService.getKvList(CollectionConstant.CLT_REFUND_WAY, WebBaseConstant.SYS_SYS_CD, WebBaseConstant.SYS_P_ORG_CD);
        SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
        condition.setPkId(applyId);
        condition.setSysCd(WebBaseConstant.SYS_SYS_CD);//系统代码
        condition.setOrgCd(WebBaseConstant.SYS_P_ORG_CD);
        condition.setCfgCd(CollectionConstant.CLT_AUTH_FILE_CFG_FLOW);
        List<SysUlFilesRecDTO> recList = this.uploadApiService.searchSysUlFilesRecList(condition);
        if (CollectionUtils.isNotEmpty(recList)) {
            ArrayList<Long> fileIds = new ArrayList<>(recList.size());
            for (SysUlFilesRecDTO sysUlFilesRecDTO : recList) {
                fileIds.add(sysUlFilesRecDTO.getId());
            }
            view.addObject("fileIds", fileIds); //附件Ids
        }
        view.addObject("applyId", applyId);
        view.addObject("taskFlag", taskFlag);
        view.addObject("uploadUsr", CurrentThreadContext.getCurrentUserName());
        view.addObject("payWays", JSON.toJSON(payWays));
        return view;
    }

    /**
     * 初始化委外催收流程附加页面数据
     */
    @RequestMapping(value = "/initCollectionData.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object initCollectionData(HttpServletRequest request) throws BaseException {
        String applyId = request.getParameter("applyId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(applyId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.newLogger("委案申请id不存在").info();
            return result;
        }
        try {
            RskCltAuthRcvAplVO rskCltAuthRcvApl = this.rskCltAuthService.getCltAuthApl4Flow(Long.valueOf(applyId));
            if (null == rskCltAuthRcvApl) {
                throw new BaseException("无法查询委外分案申请信息");
            }
            result.setData(rskCltAuthRcvApl);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("初始化委案催收流程附加页面数据异常").setKeys("applyId:" + applyId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.newLogger("初始化委案催收流程附加页面数据异常").setKeys("applyId:" + applyId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
        }
        return result;
    }

    /**
     * 初始化文件列表
     */
    @RequestMapping(value = "/initFilesList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initFilesList(HttpServletRequest request) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String pkId = request.getParameter("pkId");
        String tabNm = request.getParameter("tabNm");
        try {
            Pager page = new Pager();
            if (StringUtils.isNotEmpty(currentPage)) {
                page.setCurrentPage(Integer.parseInt(currentPage));
            }
            if (StringUtils.isNotEmpty(pageSize)) {
                page.setEveryPage(Integer.parseInt(pageSize));
            }
            SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
            if (StringUtils.isEmpty(pkId) || StringUtils.isEmpty(tabNm)) {
                return page;
            }
            String sysCd = CurrentThreadContext.getCurrentSysCd();
            qc.setPkId(pkId);
            // 判断标识确定文件配置编码
            qc.setCfgCd(CollectionConstant.CLT_AUTH_FILE_CFG_FLOW);
            qc.setTabNm(tabNm);
            qc.setSysCd(sysCd);//系统代码-必须条件
            page.setCondition(qc);
            List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(qc);
            // 遍历list查询文件上传者-真实姓名
            SysUsrVO usrVo = null;
            if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
                for (SysUlFilesRecVO vo : list) {
                    usrVo = this.sysUsrService.selectById(vo.getCrtUsrId(), sysCd);
                    vo.setCrtUsrRlNm(usrVo.getRefRlNm());
                }
            }
            page.setResultList(list);
            page.setTotalCount(list.size());
            ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, list.size());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询委案催收文件列表失败").setKeys("pkId:" + pkId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询委案催收文件列表失败").setKeys("pkId:" + pkId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 保存委案催收附件信息
     */
    @RequestMapping(value = "/uploadAttchment.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object uploadAttchment(HttpServletRequest request) throws BaseException {
        String attchmnt = request.getParameter("docArray");
        String id = request.getParameter("pkId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        if (StringUtils.isNotEmpty(attchmnt) && StringUtils.isNotEmpty(id)) {
            // 上传解析
            try {
                // 文件说明
                String fileRem = "委案催收文件上传";
                // 数据表名
                String tabNm = CollectionConstant.TAB_NM;
                // 文件配置
                String cfgCd = CollectionConstant.CLT_AUTH_FILE_CFG_FLOW;
                // 组织架构
                String cfgOrgCd = AssFileConstant.ASS_TRAIL_CAR_CFGORG;
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(id, attchmnt, cfgCd, "10", tabNm, fileRem, null, null, false, cfgOrgCd);
                if (null == attchmntPass || attchmntPass == false) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("委案催收附件信息上传失败!");
                    BaseLogUtils.newLogger("委案催收附件信息上传失败").setKeys("pkId:" + id).info();
                }
                result.setData(id);
            } catch (BaseException ex) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(ex.getMessage());
                BaseLogUtils.newLogger("委案催收附件信息上传失败").setKeys("pkId:" + id, "docArray:" + attchmnt).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            } catch (Exception ex) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.newLogger("委案催收附件信息上传失败").setKeys("pkId:" + id, "docArray:" + attchmnt).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            }
        }
        return result;
    }

    /**
     * 修改委外催收流程附加页面数据
     */
    @RequestMapping(value = "/modify4CltAuthFlow.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify4CltAuthFlow(HttpServletRequest request) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String applyId = request.getParameter("applyId");
        String payer = request.getParameter("payer");
        String payDt = request.getParameter("payDt");
        String recoveryAmt = request.getParameter("recoveryAmt");
        String payWay = request.getParameter("payWay");
        String isStlAmt = request.getParameter("isStlAmt");
        String isResolve = request.getParameter("isResolve");
        if (StringUtils.isEmpty(applyId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.newLogger("委案申请id不存在").info();
            return result;
        }
        try {
            RskCltAuthRcvAplVO entity = new RskCltAuthRcvAplVO();
            entity.setId(Long.valueOf(applyId));
            if (StringUtils.isNotEmpty(payer)) {
                entity.setPayer(payer);
            }
            if (StringUtils.isNotEmpty(payDt)) {
                entity.setPayDt(DateUtils.formatStringToDate(payDt, DateUtils.YYYY_MM_DD));
            }
            if (StringUtils.isNotEmpty(recoveryAmt)) {
                entity.setRecoveryAmt(DecimalUtils.convertYuanToFen(Double.valueOf(recoveryAmt)));
            }
            if (StringUtils.isNotEmpty(payWay)) {
                entity.setPayWay(payWay);
            }
            if (StringUtils.isNotEmpty(isStlAmt)) {
                entity.setIsStlAmt(Integer.parseInt(isStlAmt));
            }
            if (StringUtils.isNotEmpty(isResolve)) {
                entity.setIsResolve(Integer.parseInt(isResolve));
            }
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());
            boolean success = this.rskCltAuthService.modifyRskCltAuthRcvApl(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            }
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("修改委外催收流程附加页面数据失败").setKeys("applyId:" + applyId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("修改委外催收流程附加页面数据失败").setKeys("applyId:" + applyId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }

    /**
     * 跳转到流程跟踪页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/showFlowTracePage.do", method = {RequestMethod.GET})
    public ModelAndView showFlowTracePage(HttpServletRequest request) {
        String cltAuthId = request.getParameter("cltAuthId");
        ModelAndView view = new ModelAndView("collection/flow/cltAuthFlowList");
        view.addObject("cltAuthId", cltAuthId);
        return view;
    }

    /**
     * 初始化流程跟踪列表数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/initFlowTraceList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initFlowTraceList(HttpServletRequest request) {
        String cltAuthId = request.getParameter("cltAuthId");
        try {
            if (StringUtils.isEmpty(cltAuthId)) {
                throw new BaseException("请求参数：委外催收ID不能为空！");
            }
            List<ProjectFlowSHDTO> list = rskCltAuthRebateService.searchFlowListByCltAuthId(Long.parseLong(cltAuthId));

            return new ListPageVO<>(list, list.size());
        } catch (BaseException e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "初始化流程跟踪列表数据业务异常！" + cltAuthId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger(CurrentThreadContext.getCurrentUserName() + "初始化流程跟踪列表数据系统异常！" + cltAuthId).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }


}
